import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../utils/app_icons.dart';
import '../../config/app_theme.dart';
import '../../providers/app_state.dart';
import 'favorite_posts_screen.dart';
import 'favorite_pets_screen.dart';
import 'favorite_videos_screen.dart';
import 'history_screen.dart';
import 'settings_screen.dart';

class ProfileScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appState = Provider.of<AppState>(context);
    final bool isLoggedIn = appState.currentUserId != null;

    return Scaffold(
      appBar: AppBar(
        title: Text('我的'),
        actions: [
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => SettingsScreen(),
                ),
              );
            },
          ),
        ],
      ),
      body: isLoggedIn ? _buildLoggedInView(context) : _buildLoginView(context),
    );
  }

  Widget _buildLoginView(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            AppIcons.logoLarge,
            width: 100,
            height: 100,
          ),
          SizedBox(height: 24),
          Text(
            '登录获取更多功能',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: () {
              // 模拟登录
              Provider.of<AppState>(context, listen: false).login('user_123');
              
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('登录成功')),
              );
            },
            style: ElevatedButton.styleFrom(
              primary: AppTheme.primaryColor,
              padding: EdgeInsets.symmetric(horizontal: 32, vertical: 12),
            ),
            child: Text('立即登录'),
          ),
        ],
      ),
    );
  }

  Widget _buildLoggedInView(BuildContext context) {
    final appState = Provider.of<AppState>(context);
    
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildUserInfo(context),
          Divider(height: 1),
          _buildToolsGrid(context),
          Divider(height: 1),
          _buildFavoritesSection(context, appState),
          Divider(height: 1),
          _buildHistorySection(context, appState),
        ],
      ),
    );
  }

  Widget _buildUserInfo(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16.0),
      color: Colors.white,
      child: Row(
        children: [
          CircleAvatar(
            radius: 40,
            backgroundImage: NetworkImage('https://via.placeholder.com/80'),
          ),
          SizedBox(width: 16),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '宠物爱好者',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 4),
                Text(
                  '爱宠无限，乐在分享',
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.grey[600],
                  ),
                ),
                SizedBox(height: 8),
                Row(
                  children: [
                    _buildStatItem('关注', '12'),
                    SizedBox(width: 16),
                    _buildStatItem('粉丝', '45'),
                    SizedBox(width: 16),
                    _buildStatItem('获赞', '98'),
                  ],
                ),
              ],
            ),
          ),
          IconButton(
            icon: Icon(Icons.edit, color: AppTheme.primaryColor),
            onPressed: () {
              // TODO: 编辑个人资料
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('编辑个人资料功能即将上线')),
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildStatItem(String title, String count) {
    return Column(
      children: [
        Text(
          count,
          style: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 16,
          ),
        ),
        Text(
          title,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
      ],
    );
  }

  Widget _buildToolsGrid(BuildContext context) {
    final tools = [
      {
        'icon': Icons.pets,
        'title': '我的宠物',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('我的宠物功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.local_activity,
        'title': '我的活动',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('我的活动功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.shopping_bag,
        'title': '我的订单',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('我的订单功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.location_on,
        'title': '我的地址',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('我的地址功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.help_outline,
        'title': '帮助中心',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('帮助中心功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.feedback,
        'title': '意见反馈',
        'onTap': () {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('意见反馈功能即将上线')),
          );
        },
      },
      {
        'icon': Icons.logout,
        'title': '退出登录',
        'onTap': () {
          _showLogoutDialog(context);
        },
      },
    ];

    return Container(
      color: Colors.white,
      padding: EdgeInsets.symmetric(vertical: 16),
      child: GridView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          childAspectRatio: 1,
        ),
        itemCount: tools.length,
        itemBuilder: (context, index) {
          final tool = tools[index];
          return InkWell(
            onTap: tool['onTap'] as Function(),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  tool['icon'] as IconData,
                  color: AppTheme.primaryColor,
                ),
                SizedBox(height: 8),
                Text(
                  tool['title'] as String,
                  style: TextStyle(fontSize: 12),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  Widget _buildFavoritesSection(BuildContext context, AppState appState) {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '我的收藏',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              TextButton(
                onPressed: () {
                  if (appState.favoritePets.isEmpty && 
                      appState.favoritePosts.isEmpty && 
                      appState.favoriteVideos.isEmpty) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('暂无收藏内容')),
                    );
                    return;
                  }
                  
                  _showClearFavoritesDialog(context);
                },
                child: Row(
                  children: [
                    Icon(Icons.delete_outline, size: 16),
                    SizedBox(width: 4),
                    Text('清空'),
                  ],
                ),
                style: TextButton.styleFrom(
                  primary: Colors.grey[600],
                ),
              ),
            ],
          ),
          SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildFavoriteItem(
                context,
                Icons.pets,
                '收藏宠物',
                appState.favoritePets.length.toString(),
                () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FavoritePetsScreen(),
                    ),
                  );
                },
              ),
              _buildFavoriteItem(
                context,
                Icons.article,
                '收藏帖子',
                appState.favoritePosts.length.toString(),
                () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FavoritePostsScreen(),
                    ),
                  );
                },
              ),
              _buildFavoriteItem(
                context,
                Icons.video_library,
                '收藏视频',
                appState.favoriteVideos.length.toString(),
                () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => FavoriteVideosScreen(),
                    ),
                  );
                },
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildHistorySection(BuildContext context, AppState appState) {
    // 计算总的浏览历史数量
    final totalHistory = appState.recentlyViewedPets.length +
        appState.recentlyViewedPosts.length +
        appState.recentlyViewedVideos.length;

    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '浏览历史',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              TextButton(
                onPressed: () {
                  if (totalHistory == 0) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('暂无浏览历史')),
                    );
                    return;
                  }
                  
                  _showClearHistoryDialog(context);
                },
                child: Row(
                  children: [
                    Icon(Icons.delete_outline, size: 16),
                    SizedBox(width: 4),
                    Text('清空'),
                  ],
                ),
                style: TextButton.styleFrom(
                  primary: Colors.grey[600],
                ),
              ),
            ],
          ),
          SizedBox(height: 16),
          InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => HistoryScreen(),
                ),
              );
            },
            child: Row(
              children: [
                Container(
                  width: 64,
                  height: 64,
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Icon(
                    Icons.history,
                    color: AppTheme.primaryColor,
                    size: 32,
                  ),
                ),
                SizedBox(width: 16),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '共浏览 $totalHistory 项内容',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 4),
                    Text(
                      '点击查看详细浏览记录',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
                Spacer(),
                Icon(
                  Icons.arrow_forward_ios,
                  size: 16,
                  color: Colors.grey,
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildFavoriteItem(
    BuildContext context,
    IconData icon,
    String title,
    String count,
    VoidCallback onTap,
  ) {
    return InkWell(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              color: Colors.grey[200],
              borderRadius: BorderRadius.circular(32),
            ),
            child: Icon(
              icon,
              color: AppTheme.primaryColor,
              size: 32,
            ),
          ),
          SizedBox(height: 8),
          Text(
            title,
            style: TextStyle(fontSize: 14),
          ),
          SizedBox(height: 4),
          Text(
            count,
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('退出登录'),
          content: Text('确定要退出登录吗？'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Provider.of<AppState>(context, listen: false).logout();
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('已退出登录')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showClearFavoritesDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('清空收藏'),
          content: Text('确定要清空所有收藏内容吗？该操作不可恢复。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Provider.of<AppState>(context, listen: false).clearAllFavorites();
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('已清空所有收藏')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }

  void _showClearHistoryDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('清空浏览历史'),
          content: Text('确定要清空所有浏览历史吗？该操作不可恢复。'),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Provider.of<AppState>(context, listen: false).clearAllHistory();
                Navigator.of(context).pop();
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('已清空所有浏览历史')),
                );
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }
} 